﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;

namespace KeyboardCountService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        Thread thread = null;
        protected override void OnStart(string[] args)
        {
            var path = Environment.CommandLine.Replace("\"", "");
            thread = new Thread(o =>
            {
                while (true)
                {
                    var pList = Process.GetProcessesByName("KeyboardCount");
                    if (pList == null || pList.Length == 0)
                    {
                        var startInfo = new ProcessStartInfo
                        {
                            FileName = new FileInfo(path).Directory.FullName + "\\KeyboardCount.exe",
                            CreateNoWindow = true,
                            UseShellExecute = false,
                            RedirectStandardOutput = false
                        };

                        var childProcess = new Process { StartInfo = startInfo };
                        childProcess.Start();
                    }

                    Thread.Sleep(1000);
                }
            });
            thread.Start();
        }

        protected override void OnStop()
        {
            if (thread!= null)
            {
                thread.Abort();
            }

            Thread.Sleep(3000);

            var pList = Process.GetProcessesByName("KeyboardCount");
            foreach (var p in pList)
            {
                p.Kill();
            }
        }
    }
}
